/*
 * Copyright (c) 2025 STMROS Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <memory>
#include <string>
#include <vector>
#include <functional>

namespace stmconn {

// 简单的消息结构定义
typedef struct {
  uint8_t system_id;      // 系统ID
  uint8_t component_id;   // 组件ID
  uint16_t message_id;    // 消息ID
  std::vector<uint8_t> payload;  // 负载数据
} StmLinkMessage;

// 错误码定义
enum class ErrorCode {
  NONE = 0,
  CONNECTION_FAILED,
  TIMEOUT,
  PROTOCOL_ERROR,
  IO_ERROR
};

// 通信接口基类
class StmConnInterface {
public:
  using SharedPtr = std::shared_ptr<StmConnInterface>;
  using ReceivedCb = std::function<void(const StmLinkMessage & msg)>;
  using ClosedCb = std::function<void(void)>;
  using ErrorCb = std::function<void(ErrorCode ec)>;

  virtual ~StmConnInterface() = default;

  // 发送消息
  virtual bool send_message(const StmLinkMessage & msg) = 0;
  
  // 打开连接
  virtual bool open() = 0;
  
  // 关闭连接
  virtual void close() = 0;
  
  // 检查连接是否打开
  virtual bool is_open() const = 0;
  
  // 设置接收回调
  void set_receive_callback(ReceivedCb cb) {
    receive_cb_ = cb;
  }
  
  // 设置关闭回调
  void set_closed_callback(ClosedCb cb) {
    closed_cb_ = cb;
  }
  
  // 设置错误回调
  void set_error_callback(ErrorCb cb) {
    error_cb_ = cb;
  }
  
  // 通过URL创建连接（工厂方法）
  static SharedPtr open_url(const std::string & url);

protected:
  ReceivedCb receive_cb_;
  ClosedCb closed_cb_;
  ErrorCb error_cb_;
};

} // namespace stmconn